package demo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TimeLogInterceptor implements HandlerInterceptor {
	
	
	
	 @Override
	    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
	        long start = System.currentTimeMillis();
	        httpServletRequest.setAttribute("startTime", start);
	    	String flag = httpServletRequest.getParameter("flag");

	    	System.out.println("TimeLogInterceptor.preHandle run,"+httpServletRequest.getServletPath()+","+o+",flag="+flag);

	    	
	    	if("false".equalsIgnoreCase(flag)){
	    		
	    		return false;
	    	}
	    	// 返回 true 时 ，才会执行 controller方法 postHandle 和 afterCompletion
	        return true;
	    }
	 
	    @Override
	    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
	        Long start = (long)httpServletRequest.getAttribute("startTime");
	        if(start!=null && start>0){
	        	long time = System.currentTimeMillis()-start;
		    	System.out.println("TimeLogInterceptor.postHandle.time="+time+","+httpServletRequest.getServletPath()+","+o);
	        }
	         
	    }
	 
	    @Override
	    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
	    
	    	System.out.println("TimeLogInterceptor.afterCompletion run ,"+httpServletRequest.getServletPath()+","+o);
	    }
	
}